/*==============================================================================
EtoE ESTIMATION
Data 	: 
Folder 	: 
Date	: 2021-10-14

Creator		: Jonas Cederlof	(JC)
Description : 
Notes:


LATEST UPDATE: 	

==============================================================================*/


clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_EtoE.log"	, replace 
use		 "$datapath/A3_age55data_WC.dta"

{ // Indicate start of new job
*===============================================================================

*Indicate first observation and date for finding the first new job
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & newfirmid==firstnewfirmid) if newfirmid!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate)
format nvalsdate %tm
}
*
{ // Generate EE-transistion indicator
*===============================================================================
forvalues t=0(1)24 {
	local j = `t'-1
	*Indicate transition from notification to a new job without non-employment inbetween (i.e EtoE)
	qui bys lopnr (eventtime_def): egen nonemp`t'= max(atfirm2==0 & working2==0 & otherfirm2==0 ) if  date<=nvalsdate & nvalsdate!=. & inrange(eventtime_def,0,`t')
	qui bys lopnr (eventtime_def) : egen EtoE`t' = max(nonemp`t'==0 & otherfirm2==1) 
	if `t'>0{
		qui replace EtoE`t' = 1 if EtoE`j'==1
	}	
	qui sum EtoE`t' if nvals==1
}


qui bys lopnr (eventtime_def) : egen nonemp= max(working2==0) if inrange(date,notdate_def,nvalsdate)

forvalues t=0(1)24 {
	local j = `t'-1
	qui bys lopnr (eventtime_def) : egen xEUE`t' = max(otherfirm2==1 & EtoE`t'==0 & nonemp==1) if   inrange(eventtime_def,0,`t')
	qui bys lopnr (eventtime_def) : egen EUE`t' = max(xEUE`t')
	if `t'>0{
		qui replace EUE`t' = 1 if EUE`j'==1
	}	
}

*Indicator for having left notifying firm
forvalues t=0(1)24 {
	local j = `t'-1
	qui bys lopnr (eventtime_def) : egen leftfirm`t' = max(atfirm2==0)  if   inrange(eventtime_def,0,`t')
	if `t'>0{
		qui replace leftfirm`t' = 1 if leftfirm`j'==1
	}	
}


*Fill in data to long format
qui gen EtoE=.
qui gen EUE=.
qui gen leftfirm = . 
forvalues t=0(1)24{	
	qui replace EtoE = EtoE`t' if eventtime_def==`t'  
	qui replace EUE = EUE`t' if eventtime_def==`t'
	qui replace leftfirm = leftfirm`t' if eventtime_def==`t'
}
drop xEUE1-xEUE24 EUE1-EUE24 EtoE1-EtoE24

*Recalls
qui bys lopnr eventtime_def : gen recall = atfirm2==1 & leftfirm==1
qui replace recall=0 if EtoE==1 | EUE==1 // Don't allow recalls after having found a new job

*Employment to unemployment
qui bys lopnr eventtime_def : gen EU = EtoE==0 & EUE==0 & atfirm2==0 & working2==0
}
*
{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "		
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
{ // Descripive graph over flows
*===============================================================================
preserve

*Condition on working at notifying firm at t=0
gen xat1 =  atfirm2==1 if eventtime_def==0
bys lopnr: egen at1 = max(xat1)
keep if at1==1


keep if inrange(eventtime_def,0,24)
gcollapse (mean) leftfirm recall otherfirm2 EUE EtoE EU ,by(eventtime_def)
	
	

gen EE= EUE + EtoE
gen EU2 = EE + EU
gen AF = 1-leftfirm 
gen AF2 = 1- leftfirm + EU2
gen RE = AF2 + recall

gen temp =1-leftfirm
gen tot = (1-leftfirm) + recall + EUE + EtoE + EU
order temp recall EUE EtoE EU tot
sum tot
	
twoway (area  RE AF2 EU2 EE EUE   eventtime_def, acolor(maroon%20 maroon%40 navy%25 navy%50 navy)) ///
(pcarrowi 0.92 19.9 0.98 20.5, lc(white) mc(white)) ///
, graphregion(color(white)) yscale(r(0 1)) ylab(0(.2)1) ///
text(.82 2 "{bf:At notifying firm}", placement(east) color(white)) ///
text(.652 11.8 "{bf:Non-employed}", placement(east) color(white)) ///
text(.352 11.8 "{bf:Employed (EE-transitions)}", placement(east) color(white)) ///
text(.07 12.8 "{bf:Employed (EUE-transitions)}", placement(east) color(white)) ///
text(.925 16.5 "{bf:Recalled}", placement(east) color(white)) ///
legend(off) xt("Months relative to notification") yt("Share in different states") ///
xl(0 6 12 18 24)

graph export "$agegraphpath/Descriptive/EE_transitions.pdf",replace	
graph export "$agegraphpath/Descriptive/EE_transitions.eps",replace	as(eps)
restore
}
*	
{ // Graph: RD-estiamtes of all transitions
*===============================================================================
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

xtset ym_def
matrix Ball = J(25,14,.) 

*Seperate graphs of treatment and control estimates
preserve
	gen at = 1 - leftfirm
	
	*Condition on working at notifying firm at t=0
	gen xat1 =  atfirm2==1 if eventtime_def==0
	bys lopnr: egen at1 = max(xat1)
	keep if at1==1

	keep if  inrange(eventtime_def,0,24) 
	foreach var of varlist EtoE EUE EU at atfirm2 recall otherfirm2 {
	local k = `k' + 1 
	local p = `k' + 7
		matrix B = J(25,4,.)
		local i = 0

		forvalues t = 0(1)24{
			local i = `i' + 1
			qui xtreg `var'		$instrument $linear $covariets 	if eventtime_def==`t' , cluster(varselid) fe nonest 
			matrix Ball[`i',`k'] =  _b[treat]
			matrix Ball[`i',`p'] =  _se[treat]
		}

	}
restore

svmat Ball


*Combined graph of RD-estimates with CI's
preserve
	keep Ball1-Ball14
	keep in 1/25
	gen t = _n - 1

	rename Ball1	EtoE
	rename Ball2	EUE
	rename Ball3	EU
	rename Ball4	atfirm
	rename Ball5	atfirm2
	rename Ball6	recall
	rename Ball7	otherfirm2
	
	rename Ball8	SE_EtoE
	rename Ball9	SE_EUE
	rename Ball10	SE_EU
	rename Ball11	SE_atfirm
	rename Ball12	SE_atfirm2
	rename Ball13	SE_recall
	rename Ball14	SE_otherfirm2
	
	*save "$datapath/DS_EE_estimates.dta",replace
	
	rename EtoE EE
	rename SE_EtoE SE_EE
	foreach vv in EE EUE EU atfirm {
		gen `vv'_c1 = `vv' + 1.96*SE_`vv'
		gen `vv'_c2 = `vv' - 1.96*SE_`vv'
	}

	rename t eventtime
	gen eventtime2 = eventtime+ 0.05
	gen eventtime3 = eventtime- 0.05
	gen temp = 0 

	twoway ///
	/// (rarea atfirm_c1 atfirm_c2 eventtime, color(gs10%50) lc(gs13)) ///
	(rarea EE_c1 EE_c2 eventtime2, color(gs10%50) lc(gs13)) ///
	(rarea EUE_c1 EUE_c2 eventtime3, color(gs10%50) lc(gs13)) ///
	(rarea EU_c1 EU_c2 eventtime3, color(gs10%50) lc(gs13)) ///
	(line atfirm  eventtime, lc(maroon*1.3) lw(medthick)) ///
	(line EE  eventtime2, lc(maroon*1.6) lw(medthick) lp(shortdash) ) ///
	(line EUE  eventtime3,lc(maroon) lw(medthick) lp(dot)) ///
	(line  EU  eventtime3, lc(navy) lw(medthick) lp(longdash) ) ///
	, graphregion(color(white)) ///
	xt("Months relative to notification") ///
	yt("Effect of MN on labor market states") xl(0(6)24) ///
	yline(0, lc(gs2)) ///
	legend(order(4 "At notifying firm" 5 "Employed (EE-transitions)" 6 "Employed (EUE-transitions)" 7 "Non-employed") region(lcolor(white)) size(small) col(1) ring(0) pos(2)) 
	graph export "$agegraphpath/Event/event_EEtrans_RD_estimates.pdf",replace
	graph export "$agegraphpath/Event/event_EEtrans_RD_estimates.eps",replace as(eps)
	

restore	
	


drop Ball*
}
*

log close

/*

{ // Graph: RD stack 
*===============================================================================
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

xtset ym_def
matrix Ball = J(26,10,.) 

*Seperate graphs of treatment and control estimates
preserve
	gen at = 1 - leftfirm
	*Condition on working at notifying firm at t=0
	gen xat1 =  atfirm2==1 if eventtime_def==0
	bys lopnr: egen at1 = max(xat1)
	keep if at1==1

	keep if  inrange(eventtime_def,0,24) 
	gen EE_EUE = (EtoE==1 | EUE==1)
	gen EE_EUE_EU = (EtoE==1 | EUE==1 | EU==1)
	local k=0
	local p=0
	local q=0
	foreach var of varlist EtoE EE_EUE EE_EUE_EU{
	local k = `k' + 1 
	local p = `k' + 3
	local q = `k' + 6
		matrix B = J(25,4,.)
		local i = 0

		forvalues t = 0(1)24{
			local i = `i' + 1
			qui xtreg `var'		$instrument $linear $covariets 	if eventtime_def==`t' , cluster(varselid) fe nonest 

			matrix B[`i',1]  = `t'
			matrix B[`i',2]  = _b[_cons]
			matrix B[`i',3]  = _b[_cons] + _b[treat]
			matrix B[`i',4]  = abs(_b[treat]/_se[treat]) >invttail(e(df_r),0.025)
			matrix Ball[`i',`k'] =  _b[treat]
			matrix Ball[`i',`p'] =  _b[_cons]
			matrix Ball[`i',`q'] = abs(_b[treat]/_se[treat]) >invttail(e(df_r),0.025)
		}

		svmat B
		rename B1 t
		rename B2 C
		rename B3 T
		rename B4 sig

		*Graph


		twoway (connected T t, `Tstyle') (connected C t, `Cstyle') (rspike T C t if sig==1, `Sstyle') ///
		,xline(0, lstyle(foreground) lpattern(dash) lcolor(black)) xscale(r(0 24)) xlabel(-0(3)24)  ///
		xtitle("Months relative to notification") ytitle("Pr(`var')") name(`var',replace) ///
		graphregion(color(white)) legend(order( 1 "Long notification" 2 "Short notification" ) region(color(white)))
		*graph export "$agegraphpath/Event/event_`var'.pdf",replace

		drop t C T sig 
	}
restore

matrix list Ball
svmat Ball


*Combined graph of RD-estimates with CI's
preserve
	keep Ball1-Ball9
	keep in 1/25
	gen t = _n - 1
	
	rename Ball1	T_EE
	rename Ball2	T_EE_EUE
	rename Ball3	T_EE_EUE_EU
	rename Ball4	C_EE
	rename Ball5	C_EE_EUE
	rename Ball6	C_EE_EUE_EU
	rename Ball7	S_EE
	rename Ball8	S_EE_EUE
	rename Ball9	S_EE_EUE_EU
	
	
	gen  F1 = C_EE + T_EE
	gen  F2 = C_EE_EUE + T_EE_EUE
	gen  F3 = C_EE_EUE_EU + T_EE_EUE_EU
	
	twoway 	(connected F1 C_EE F2 C_EE_EUE F3  C_EE_EUE_EU t , ///
	mcolor(black black black black black black) ///
	lcolor(black black black black black black) ///
	lpattern(solid dash solid dash solid dash) ///
	ms(o oh T Th S Sh )) ///
	(rspike F1 C_EE 	t if S_EE==1, lpattern(shortdash_dot) lcolor(navy) vertical) ///
	(rspike F2 C_EE_EUE 	t if S_EE_EUE==1, lpattern(shortdash_dot) lcolor(navy) vertical) ///
	(rspike F3 C_EE_EUE_EU 	t if S_EE_EUE_EU==1, lpattern(shortdash_dot) lcolor(navy) vertical) ///
	,legend(off) ///
	text(.2 15 "EE", place(e) color(black)) ///
	text(.45 20 "EUE", place(e) color(black)) ///
	text(.7 15.5 "Non-employment", place(e) color(black)) ///
	text(.82 4 "At notifying firm", place(e) color(black)) ///
	graphregion(color(white)) xtitle("Months relative to notification") ytitle("Cumulative share") ///
	xlab(0(6)24) ///
	name(stack,replace)
	
	graph export "$agegraphpath/Event/event_RDstack_EEtrans.pdf",replace
restore



}
*
{ // Graph RD: Pr(EE transistion) 
*===============================================================================
*==========
xtset ym_def
*===========
*Set time period to look at
local t = 6

preserve
	local outcome "EtoE"
	
	keep if eventtime_def==`t'
	gen freq=1
	xtreg `outcome'			$instrument $linear $covariets 	 , cluster(varselid) fe nonest 
	local beta = round(_b[treat],0.0001)
	local se   = round(_se[treat],0.0001)
	
	*Residulize year*moth fixed effects
	xtreg `outcome'		$covariets  , cluster(varselid) fe nonest 
	predict e, e
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	*Fix bins of runvar
	gen 	bin = round(runvar*12)
	egen 	bin2 = cut(bin) , at(-36(2)1)
	egen 	bin3 = cut(bin), at(1(2)36)
	gen 	bin4 = bin2
	replace bin4 = bin3 if bin4==.
	replace bin4 = bin4 + 0.5
	bys bin4: egen `outcome'_bin = mean(`outcome')
	tab  runvar bin4
	
	
	
	collapse (mean) `outcome' `outcome'_bin  (sum) freq, by(runvar bin4 treat)
	
	replace runvar = runvar*12
	
	local lineopt 	"lpattern(dash) lcolor(black) lstyle(foreground)"
	*Linear Fit
	twoway 	(scatter `outcome'_bin  bin4 		 	 , ms(o) mcolor(black))  		///	 	
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==0, lcolor(black)) 	 		///
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==1, lcolor(black))	 		///
		, xline(0 , `lineopt')  legend(off) graphregion(color(white)) 					///
		  xscale(r(-36 36)) xlabel(-36(12)36) 	name(a,replace)					///
		  xtitle("Normalized age (months)") ytitle("Pr(EE transition within `t' months of finding a job)") ///
		  note("Note: b=`beta' (`se') ", size(vsmall))		
	graph export "$agegraphpath/RD/RD_EEtransition _within`t'.pdf", replace
restore		
}
*


